<template>
  <div class="tag-manager">
    <div class="tag-header">
      <h2>标签管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>
        添加标签
      </el-button>
    </div>
    
    <div class="tag-list">
      <el-table :data="tags" style="width: 100%">
        <el-table-column prop="name" label="标签名称" min-width="200">
          <template #default="{ row }">
            <div class="tag-name">
              <el-tag>{{ row.name }}</el-tag>
              <span class="tag-count">({{ getTagCount(row.name) }})</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="confirmDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 添加/编辑标签对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑标签' : '添加标签'"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入标签名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useEmojiStore } from '../stores/emoji'
import { ElMessageBox, ElMessage } from 'element-plus'

const emojiStore = useEmojiStore()
const dialogVisible = ref(false)
const isEditing = ref(false)
const submitting = ref(false)
const formRef = ref(null)

const form = ref({
  id: null,
  name: ''
})

const rules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取标签列表
const tags = computed(() => emojiStore.tags)

// 获取标签使用次数
const getTagCount = (tagName) => {
  return emojiStore.emojis.filter(emoji => emoji.tags.includes(tagName)).length
}

// 显示添加对话框
const showAddDialog = () => {
  isEditing.value = false
  form.value = { id: null, name: '' }
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (tag) => {
  isEditing.value = true
  form.value = { ...tag }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEditing.value) {
      // 更新标签
      await emojiStore.updateTag(form.value.id, form.value.name)
      ElMessage.success('更新成功')
    } else {
      // 添加标签
      await emojiStore.addTag(form.value.name)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 确认删除
const confirmDelete = (tag) => {
  const count = getTagCount(tag.name)
  if (count > 0) {
    ElMessageBox.confirm(
      `该标签正在被 ${count} 个表情包使用，删除后这些表情包的标签将被移除。确定要删除吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        await emojiStore.deleteTag(tag.id)
        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除标签失败:', error)
        ElMessage.error('删除失败')
      }
    }).catch(() => {})
  } else {
    ElMessageBox.confirm(
      '确定要删除这个标签吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        await emojiStore.deleteTag(tag.id)
        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除标签失败:', error)
        ElMessage.error('删除失败')
      }
    }).catch(() => {})
  }
}
</script>

<style lang="scss" scoped>
.tag-manager {
  padding: 20px;
  
  .tag-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      color: #303133;
    }
  }
  
  .tag-list {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .tag-name {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .tag-count {
        color: #909399;
        font-size: 14px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
</style> 